/**
 * 
 */
package com.abel.manager.impl;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.abel.domain.Application;
import com.abel.domain.DesiredPosition;
import com.abel.domain.HelpfulInformation;
import com.abel.domain.MilitaryService;
import com.abel.domain.OptionalInformation;
import com.abel.domain.PersonProfile;
import com.abel.domain.PersonSearchCriteria;
import com.abel.domain.PersonalInformation;
import com.abel.manager.PersonProfileManager;
import com.abel.manager.exception.PersonProfileException;
import com.abel.repository.MilitaryServiceRepository;
import com.abel.repository.PersonProfileRepository;
import com.abel.repository.exception.NonExistantProfileException;
import com.abel.repository.exception.RepositoryException;
import com.abel.util.UserSessionLocator;


public class PersonProfileManagerImpl implements PersonProfileManager
{

    protected final Log logger = LogFactory.getLog(getClass());
    
    private PersonProfileRepository personalProfileRepository;

    private MilitaryServiceRepository militaryServiceRepository;

    

    /* (non-Javadoc)
     * @see com.abel.manager.ProfileManager#updatePersonalInformation(com.abel.domain.PersonalInformation)
     */
    @Override
    public void updatePersonalInfo(
            PersonalInformation personalInformation)
        throws PersonProfileException
    {
        /*
         * if personProfileid is 0, it indicates that this is a add request.
         * Else there will always be an id set when retrieved from db
         */
        Application application = UserSessionLocator.getUserSession().getPerson().getApplication();
    	
        if (application.getApplicationId() == 0) {
            try {
                int applicationId = this.personalProfileRepository.addPersonalInformation(personalInformation);
                application.setApplicationId(applicationId);
                personalInformation.setCreateDate(new Date());
                

            }
            catch (RepositoryException e)
            {
                logger.debug("@PersonProfileManagerImpl : updatePersonalInfo : exception " + e);
                e.printStackTrace();
                throw new PersonProfileException("Exception caused while adding personalinformation for " + personalInformation.getSsn(), e);
            }
     
        }
        else {
            try {
            	personalInformation.setCreateDate(application.getPersonProfile().getPersonalInformation().getCreateDate());
            	this.personalProfileRepository.updatePersonalInformation(personalInformation);
            
            }
            catch (RepositoryException e)
            {
                logger.debug("@PersonProfileManagerImpl : updatePersonalInfo : exception " + e);
                e.printStackTrace();
                throw new PersonProfileException("Exception caused while updating personalinformation for " + application.getApplicationId(), e);
            }
     
        }
        //sets person in threadlocal to be available in session
        application.getPersonProfile().setPersonalInformation(personalInformation);

    }

    
    

    /* (non-Javadoc)
	 * @see com.abel.manager.PersonProfileManager#getPersonProfile(com.abel.domain.PersonSearchCriteria)
	 */
	@Override
	public PersonProfile getPersonProfile(PersonSearchCriteria criteria)
			throws PersonProfileException, NonExistantProfileException {
		PersonProfile personProfile  = null;
		try {
			personProfile  = personalProfileRepository.getPersonProfile(criteria);
			personProfile.setMilitaryServiceInformation(this.militaryServiceRepository.getMilitaryService(criteria));
			//sets personprofile in threadlocal
			Application application = UserSessionLocator.getUserSession().getPerson().getApplication();
			
			application.setPersonProfile(personProfile);
		}
		catch (RepositoryException e) {
			
			logger.debug("@PersonProfileManagerImpl : getPersonProfile : exception " + e);
            e.printStackTrace();
            throw new PersonProfileException("Exception caused while getting personalinformation for " + criteria.getUserId(), e);
            
		}
		
		return personProfile;
	}


	/* (non-Javadoc)
	 * @see com.abel.manager.PersonProfileManager#updateOptionalInfo(com.abel.domain.OptionalInformation)
	 */
	@Override
	public void updateOptionalInfo(OptionalInformation optionalInformation)
			throws PersonProfileException {
		
        /*
         * if personProfileid is 0, it indicates that the access to this function is incorrect
         * or the personalinformation is not stored before getting to optional information
         */
        Application application = UserSessionLocator.getUserSession().getPerson().getApplication(); 
        
        if (application.getApplicationId() == 0) {

        	throw new PersonProfileException("Optional informaton is added to a non existant application.  Application id request to be updated = " + application.getApplicationId());
        }
        else {
			
        	try {
				//updating optionalinformation
				this.personalProfileRepository.updateOptionalInformation(optionalInformation);
				//setting optionalinformaton in threadlocal
				application.getPersonProfile().setOptionalInformation(optionalInformation);
				
			} catch (RepositoryException e) {
				
				logger.debug("@PersonProfileManagerImpl : updateOptionalInfo : exception " + e);
				e.printStackTrace();
				throw new PersonProfileException("Unable to update optional information for user " + 
						UserSessionLocator.getUserSession().getAuthPrincipal().getUserName(), e);
			}
        }
	}


	/* (non-Javadoc)
	 * @see com.abel.manager.PersonProfileManager#updateHelpfulInfo(com.abel.domain.HelpfulInformation)
	 */
	@Override
	public void updateHelpfulInfo(HelpfulInformation helpfulInformation)
			throws PersonProfileException {
        /*
         * if personProfileid is 0, it indicates that the access to this function is incorrect
         * or the HelpfulInformation is not stored before getting to helpful information
         */
        Application application = UserSessionLocator.getUserSession().getPerson().getApplication(); 
        
        if (application.getApplicationId() == 0) {

        	throw new PersonProfileException("Optional informaton is added to a non existant application.  Application id request to be updated = " + application.getApplicationId());
        }
		try {
            //updating helpfulinformation
        	this.personalProfileRepository.updateHelpfulInformation(helpfulInformation);
        	//setting helpfulinformation to threadlocal
        	application.getPersonProfile().setHelpfulInformation(helpfulInformation);
        
        }
        catch (RepositoryException e)
        {
            logger.debug("@PersonProfileManagerImpl : updateHelpfulInfo : exception " + e);
            e.printStackTrace();
            throw new PersonProfileException("Exception caused while updating updateHelpfulInfo for " + helpfulInformation + e);
        }
		
	}



	/* (non-Javadoc)
	 * @see com.abel.manager.PersonProfileManager#updateDesiredPostionInfo(com.abel.domain.DesiredPosition)
	 */
	@Override
	public void updateDesiredPositionInfo(DesiredPosition desiredPosition)
			throws PersonProfileException {

        /*
         * if personProfileid is 0, it indicates that the access to this function is incorrect
         * or the personalinformation is not stored before getting to optional information
         */
        Application application = UserSessionLocator.getUserSession().getPerson().getApplication(); 
        
        if (application.getApplicationId() == 0) {

        	throw new PersonProfileException("Desired Position is added to a non existant application.  Application id request to be updated = " + application.getApplicationId());
        }
        else {
			
        	try {
				//updating update desired position
				this.personalProfileRepository.updateDesiredPosition(desiredPosition);
				//setting desiredposition in threadlocal
				application.getPersonProfile().setDesiredPosition(desiredPosition);
				
			} catch (RepositoryException e) {
				
				logger.debug("@PersonProfileManagerImpl : updateDesiredPositionInfo : exception " + e);
				e.printStackTrace();
				throw new PersonProfileException("Unable to update desired postiion for user " + 
						UserSessionLocator.getUserSession().getAuthPrincipal().getUserName(), e);
			}
        }		
	}


	@Override
	public void updateMilitaryserviceInfo(MilitaryService ms)
			throws PersonProfileException 
	{
        
        Application application = UserSessionLocator.getUserSession().getPerson().getApplication(); 
        
        if (application.getApplicationId() == 0) {

        	throw new PersonProfileException("Military Service Information is added to a non existant application.  Application id request to be updated = " + application.getApplicationId());
        }
        else {
			
	        if (ms.getMltServiceId() == 0) {
	            try {
	                int mltServiceId = this.militaryServiceRepository.addMilitaryService(ms);
					ms.setMltServiceId(mltServiceId);
					application.getPersonProfile().setMilitaryServiceInformation(ms);
	                
	            }
	            catch (RepositoryException e)
	            {
					logger.debug("@PersonProfileManagerImpl : updateMilitaryserviceInfo : exception " + e);
	                e.printStackTrace();
	                throw new PersonProfileException("Exception caused while adding Military Service information for " + ms.getAplId(), e);
	            }
	     
	        }
	        else {
	            try {
	                this.militaryServiceRepository.updateMilitaryService(ms);
					application.getPersonProfile().setMilitaryServiceInformation(ms);
	            }
	            catch (RepositoryException e)
	            {
					logger.debug("@PersonProfileManagerImpl : updateMilitaryserviceInfo : exception " + e);
	                e.printStackTrace();
	                throw new PersonProfileException("Exception caused while adding Military Service information for " + ms.getAplId(), e);
	            }
	        }
        }
		
	}

	

	
	/* (non-Javadoc)
	 * @see com.abel.manager.PersonProfileManager#deleteMilitaryserviceInfo(com.abel.domain.MilitaryService)
	 */
	@Override
	public void deleteMilitaryserviceInfo(MilitaryService militaryService)
			throws PersonProfileException {
	
		Application application = UserSessionLocator.getUserSession().getPerson().getApplication(); 
		
		try {
			
			this.militaryServiceRepository.deleteMilitaryService(militaryService);
			application.getPersonProfile().setMilitaryServiceInformation(null);
		
		} 
		catch (RepositoryException e) {
		
			logger.debug("@EducationRepositoryImpl : deleteMilitaryserviceInfo : exception " + e);
			e.printStackTrace();
			throw new PersonProfileException("Exception caused while deleting Military Service information for appl id " + militaryService.getAplId(), e);
		}
	}




	@Override
    public void setPersonProfileRepository(
            PersonProfileRepository personalProfileRepository)
    {
        this.personalProfileRepository = personalProfileRepository;
        
    }

	@Override
    public void setMilitaryServiceRepository(
    		MilitaryServiceRepository militaryServiceRepository)
    {
        this.militaryServiceRepository = militaryServiceRepository;
        
    }

}
